/**
 * 
 */
package com.wubo.sec.core;

import java.util.Collection;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.vote.RoleVoter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import com.wubo.sec.model.Authority;

/**
 * @author wubo
 * @CreateDate 2010-8-9
 * @version 1.0.01
 */
public class MyRoleVoter extends RoleVoter {

	public boolean supports(ConfigAttribute attribute) {
		if((attribute.getAttribute() != null) && (attribute.getAttribute().startsWith("IS_AUTHENTICATED_") 
				|| attribute.getAttribute().startsWith("RUN_AS_") || attribute.getAttribute().startsWith("ACL_"))){
			return false;
		}
        if ((attribute.getAttribute() != null) && attribute.getAttribute().startsWith(getRolePrefix())) {
        	return true;
        }
        else {
            return false;
        }
    }
	
	public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
        int result = ACCESS_ABSTAIN;
        
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        
        for (ConfigAttribute attribute : attributes) {
            if (this.supports(attribute)) {
                result = ACCESS_DENIED;
                
                // Attempt to find a matching granted authority
                for (GrantedAuthority authority : authorities) {
                	String auth = authority.getAuthority();
                	if(auth.equals(Authority.ADMIN)){
                		return ACCESS_GRANTED;
                	}
                	System.out.println(attribute.getAttribute()+" - "+auth);
                    if (attribute.getAttribute().equals(auth)) {
                        return ACCESS_GRANTED;
                    }
                }
            }
        }
        return result;
    }
	
}
